package com.citygis.securitysystem.system.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * @ClassName: SecurityConfig 
 * @Description: TODO
 * @author: liuzg
 * @Date: 2021/1/20 16:48
 * @Version: v1.0
 */
@Configuration
@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    // 注入数据源
    @Autowired
    private DataSource dataSource;

    // 配置对象
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        // 自动生成表，已自己创建表，所以注释掉
        //jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }
    @Bean
    PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }

//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(userDetailsService).passwordEncoder(new PasswordEncoder() {
//            @Override
//            public String encode(CharSequence charSequence) {
//                return charSequence.toString();
//            }
//
//            @Override
//            public boolean matches(CharSequence charSequence, String s) {
//                return s.equals(charSequence.toString());
//            }
//        });
//    }

//    @Bean
//    PasswordEncoder password() {
//        return new BCryptPasswordEncoder();
//    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 退出
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/test/hello").permitAll();

        // 配置没有权限访问的自定义页面
        http.exceptionHandling().accessDeniedPage("/unauth.html");

        http.formLogin()   //自定义自己编写的登录页面
                .loginPage("/login.html") // 登录页面设置
                .loginProcessingUrl("/user/login")   // 登录访问路径
                .defaultSuccessUrl("/home.html").permitAll()    // 登录成功之后，跳转路径
                .and().authorizeRequests()
                    .antMatchers("/","/test/hello","/user/login").permitAll() // 设置哪些路径不需要认证
                    // 当前登录用户，只有具备admins权限才可以访问这个路径
                    //.antMatchers("/test/index").hasAuthority("admins")
                    //.antMatchers("/test/index").hasAnyAuthority("admins,manager")
                    .antMatchers("/test/index").hasRole("sale")
                .anyRequest().authenticated()

                // 设置记住我   persistentTokenRepository 操作数据库对象
                .and().rememberMe().tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(60)  // 设置有效时长，已秒为单位
                .userDetailsService(userDetailsService)  // 使用底层操作数据库
                .and().csrf().disable(); // 关闭csrf防护

    }




}
